package com.ajmd.onlineexam.config;

import com.ajmd.onlineexam.baseUtil.MyTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 *  token认证过滤器
 * @author ajmd
 * @since 2023/3/13 2:03
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    /**
     * 开启跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路由
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*")
                .exposedHeaders(HttpHeaders.SET_COOKIE);
    }

    private MyTokenInterceptor tokenInterceptor;


    //构造方法
    public CorsConfig(MyTokenInterceptor tokenInterceptor) {
        this.tokenInterceptor = tokenInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePaths = new ArrayList<>();
        //排除拦截，除了注册登录(此时还没token)和token获取(此时一般已有token)
        excludePaths.add("/student/register");
        excludePaths.add("/student/login");
        excludePaths.add("/api/refreshToken");
        excludePaths.add("/api/redis/get");//测试
        excludePaths.add("/api/redis/set");//测试
//        excludePaths.add("/img/**");
        List<String> paths = new ArrayList<>();
        paths.add("/student/**");
        paths.add("/api/**");

        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns(paths)
                .excludePathPatterns(excludePaths);
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String imgPath = System.getProperty("user.dir") + "/src/main/resources/static/";
        //将所有以/static/开头的请求路径映射到静态资源处理器上。
        registry.addResourceHandler("/static/**")
//                .addResourceLocations("classpath:/static/");
                .addResourceLocations("file:"+imgPath);
    }


}
